package datastructure.array;



/**
 * @Description: 稀疏数组-五子棋
 * @author: Yang Qiang
 * @create: 2021-10-24 16:43
 */
public class SparseArray {
    public static void main(String[] args) {
        int[][] array = new int[11][11];// 声明棋盘
        array[1][2] = 1;// 1表示黑色棋子
        array[2][3] = 2;// 2表示蓝色漆子
        /*
            遍历棋盘
            0 0 0 0 0 0 0 0 0 0 0
            0 0 1 0 0 0 0 0 0 0 0
            0 0 0 2 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
            0 0 0 0 0 0 0 0 0 0 0
         */
        print1(array);

        /*
            把二维数组棋盘压缩为稀疏数组
            1 先计算有多少个非空值
            2 构造稀疏数组
            3 打印稀疏数组
                11 11 2
                1 2 1
                2 3 2
            4 把稀疏数组恢复为二维数组

         */
        int sum = doSum(array);
        int[][] sparseArray = doCreate(sum, array);
        print1(sparseArray);
        int[][] twoArray = doRecover(sparseArray);
        print1(twoArray);

    }

    private static int[][] doRecover(int[][] sparseArray) {
        int[][] twoArray = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            twoArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        return twoArray;
    }

    private static int[][] doCreate(int sum, int[][] array) {
        // 稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        // 稀疏数组的第一行数据
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        // 稀疏数组其他的数据(遍历原来的二维数组获得)
        int rowNum = 0;//数据的行号
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0){
                    rowNum++;
                    sparseArray[rowNum][0] = i;
                    sparseArray[rowNum][1] = j;
                    sparseArray[rowNum][2] = array[i][j];

                }
            }
        }
        // 返回稀疏数组
        return sparseArray;
    }

    private static int doSum(int[][] array) {
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    sum += 1;
                }
            }
        }
        return sum;
    }

    private static void print1(int[][] array) {
        for(int[] arr : array){
            for (int item : arr){
                System.out.printf("%d ", item);
            }
            System.out.println();
        }

    }
}
